<?php
// 统一导航栏框架 - 基于权限的动态菜单系统
// 文件：/workspace/common/navigation.php

// 确保session已启动
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    header("Location: ../index.php");
    exit();
}

// 数据库连接 - 使用现有的数据库连接方式
try {
    $database_path = dirname(__FILE__) . '/../database.php';
    if (file_exists($database_path)) {
        require_once $database_path;
        $db_connected = isset($conn) && $conn instanceof mysqli;
    } else {
        $db_connected = false;
    }
} catch (Exception $e) {
    error_log("导航栏数据库连接失败: " . $e->getMessage());
    $db_connected = false;
}

/**
 * 获取用户权限 - 统一版本，只需要一个参数
 * @param string $user_id 用户ID
 * @return array 用户角色数组
 */
if (!function_exists('getUserRoles')) {
    function getUserRoles($user_id) {
        global $conn, $db_connected;

        if (!$db_connected || !$conn) {
            return [];
        }

        try {
            $stmt = $conn->prepare("SELECT role FROM user_roles WHERE user_id = ?");
            if (!$stmt) {
                error_log("准备SQL语句失败: " . $conn->error);
                return [];
            }

            $stmt->bind_param("s", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();

            $roles = [];
            while ($row = $result->fetch_assoc()) {
                $roles[] = $row['role'];
            }

            $stmt->close();
            return $roles;
        } catch (Exception $e) {
            error_log("获取用户权限失败: " . $e->getMessage());
            return [];
        }
    }
}

/**
 * 检查用户是否有特定权限
 * @param array $user_roles 用户角色数组
 * @param array $required_roles 需要的角色数组
 * @return bool 是否有权限
 */
if (!function_exists('hasPermission')) {
    function hasPermission($user_roles, $required_roles) {
        return !empty(array_intersect($user_roles, $required_roles));
    }
}

/**
 * 获取当前页面文件名
 * @return string 当前页面文件名
 */
if (!function_exists('getCurrentPage')) {
    function getCurrentPage() {
        return basename($_SERVER['PHP_SELF']);
    }
}

// 获取当前用户权限 - 修复：使用统一的单参数调用
$current_user_id = $_SESSION['user_id'];
$user_roles = getUserRoles($current_user_id);  // 只传递一个参数
$current_page = getCurrentPage();

// 定义菜单结构和权限要求
$menu_structure = [
    'system_management' => [
        'title' => '系统管理',
        'url' => 'system_management.php',
        'required_roles' => ['系统管理员'],
        'submenu' => []
    ],
    'hr_management' => [
        'title' => '人事管理',
        'url' => '#',
        'required_roles' => ['系统管理员', '人事管理员'],
        'submenu' => [
            'serving_staff' => [
                'title' => '在职员工',
                'url' => 'serving_staff.php',
                'required_roles' => ['系统管理员', '人事管理员']
            ],
            'retired_staff' => [
                'title' => '退休员工',
                'url' => 'retired_staff.php',
                'required_roles' => ['系统管理员', '人事管理员']
            ]
        ]
    ],
    'room_management' => [
        'title' => '课室管理',
        'url' => '#',
        'required_roles' => ['系统管理员', '考试项目管理员'],
        'submenu' => [
            'rooms_display' => [
                'title' => '展示课室信息',
                'url' => 'rooms_display.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ],
            'add_room' => [
                'title' => '添加课室',
                'url' => 'add_room.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ]
        ]
    ],
    'exam_signup' => [
        'title' => '填报监考意愿',
        'url' => 'exam_signup_list.php',
        'required_roles' => ['系统管理员', '考试项目管理员', '人事管理员', '普通账号'],
        'submenu' => []
    ],
    'project_management' => [
        'title' => '项目管理',
        'url' => '#',
        'required_roles' => ['系统管理员', '考试项目管理员'],
        'submenu' => [
            'exam_projects' => [
                'title' => '展示考试项目',
                'url' => 'exam_projects.php',
                'required_roles' => ['考试项目管理员']
            ],
            'create_exam_project' => [
                'title' => '新建考试项目',
                'url' => 'create_exam_project.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ],
            'arrange_rooms_invigilators' => [
                'title' => '考场管理',
                'url' => 'arrange_rooms_invigilators.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ],
            'signup_management' => [
                'title' => '报名管理',
                'url' => 'signup_management.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ],
            'violations_display' => [
                'title' => '违规管理',
                'url' => 'violations_display_all.php',
                'required_roles' => ['系统管理员', '考试项目管理员']
            ]
        ]
    ]
];

/**
 * 生成导航栏HTML - 安全版本
 */
if (!function_exists('generateNavigation')) {
    function generateNavigation($menu_structure, $user_roles, $current_page) {
        $html = '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">';
        $html .= '<div class="container-fluid">';

        // 品牌标识
        $html .= '<a class="navbar-brand" href="user_home.php">🎓 考务管理系统</a>';

        // 响应式按钮
        $html .= '<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">';
        $html .= '<span class="navbar-toggler-icon"></span>';
        $html .= '</button>';

        // 导航菜单
        $html .= '<div class="collapse navbar-collapse" id="navbarNav">';
        $html .= '<ul class="navbar-nav me-auto">';

        // 首页链接
        $home_active = ($current_page == 'user_home.php') ? 'active' : '';
        $html .= '<li class="nav-item">';
        $html .= '<a class="nav-link ' . $home_active . '" href="user_home.php">首页</a>';
        $html .= '</li>';

        // 生成菜单项
        foreach ($menu_structure as $key => $menu_item) {
            // 检查权限
            if (!hasPermission($user_roles, $menu_item['required_roles'])) {
                continue;
            }

            $has_submenu = !empty($menu_item['submenu']);
            $is_active = false;

            // 检查当前页面是否属于此菜单
            if ($current_page == basename($menu_item['url'])) {
                $is_active = true;
            } else if ($has_submenu) {
                foreach ($menu_item['submenu'] as $submenu_item) {
                    if ($current_page == basename($submenu_item['url'])) {
                        $is_active = true;
                        break;
                    }
                }
            }

            $active_class = $is_active ? 'active' : '';

            if ($has_submenu) {
                // 有子菜单的项目
                $html .= '<li class="nav-item dropdown">';
                $html .= '<a class="nav-link dropdown-toggle ' . $active_class . '" href="#" id="' . $key . 'Dropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">';
                $html .= htmlspecialchars($menu_item['title']);
                $html .= '</a>';
                $html .= '<ul class="dropdown-menu" aria-labelledby="' . $key . 'Dropdown">';

                foreach ($menu_item['submenu'] as $submenu_key => $submenu_item) {
                    if (hasPermission($user_roles, $submenu_item['required_roles'])) {
                        $submenu_active = ($current_page == basename($submenu_item['url'])) ? 'active' : '';
                        $html .= '<li><a class="dropdown-item ' . $submenu_active . '" href="' . htmlspecialchars($submenu_item['url']) . '">' . htmlspecialchars($submenu_item['title']) . '</a></li>';
                    }
                }

                $html .= '</ul>';
                $html .= '</li>';
            } else {
                // 无子菜单的项目
                $html .= '<li class="nav-item">';
                $html .= '<a class="nav-link ' . $active_class . '" href="' . htmlspecialchars($menu_item['url']) . '">' . htmlspecialchars($menu_item['title']) . '</a>';
                $html .= '</li>';
            }
        }

        $html .= '</ul>';

        // 用户信息和登出
        $html .= '<ul class="navbar-nav">';
        $html .= '<li class="nav-item dropdown">';
        $html .= '<a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">';
        $html .= '<i class="fas fa-user"></i> ' . htmlspecialchars($_SESSION['username'] ?? $_SESSION['user_id'] ?? '未知用户');
        $html .= '</a>';
        $html .= '<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">';
        $html .= '<li><a class="dropdown-item" href="user_profile.php"><i class="fas fa-user-cog"></i> 个人设置</a></li>';
        $html .= '<li><hr class="dropdown-divider"></li>';
        $html .= '<li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt"></i> 退出登录</a></li>';
        $html .= '</ul>';
        $html .= '</li>';
        $html .= '</ul>';

        $html .= '</div>';
        $html .= '</div>';
        $html .= '</nav>';

        return $html;
    }
}

/**
 * 渲染导航栏 - 主要渲染函数
 * @param bool $output_content 是否输出HTML内容，默认为true
 */
if (!function_exists('renderNavigationBar')) {
    function renderNavigationBar($output_content = true) {
        global $menu_structure, $user_roles, $current_page;

        // 如果定义了SENDING_HEADERS常量且为true，则不输出内容
        if (defined('SENDING_HEADERS') && SENDING_HEADERS) {
            $output_content = false;
        }

        // 生成导航栏HTML
        $navigation_html = generateNavigation($menu_structure, $user_roles, $current_page);

        // 如果不需要输出内容，则直接返回
        if (!$output_content) {
            return $navigation_html;
        }

        // 输出CSS样式
        echo '<style>
        .navbar-nav .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        .dropdown-item.active {
            background-color: #0d6efd;
            color: white;
        }

        .dropdown-item:hover {
            background-color: #f8f9fa;
        }

        .navbar-brand {
            font-weight: bold;
            font-size: 1.3rem;
        }

        .nav-link {
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1);
            border-radius: 4px;
        }

        .dropdown-menu {
            border: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        @media (max-width: 991px) {
            .navbar-nav {
                padding-top: 1rem;
            }

            .dropdown-menu {
                border: 1px solid #dee2e6;
                margin-top: 0.5rem;
            }
        }
        </style>';

        // 输出导航栏HTML
        echo $navigation_html;

        // 输出JavaScript
        echo '<script>
        document.addEventListener("DOMContentLoaded", function() {
            // 确保Bootstrap下拉菜单正常工作
            if (typeof bootstrap !== "undefined") {
                var dropdownElementList = [].slice.call(document.querySelectorAll(".dropdown-toggle"));
                var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
                    return new bootstrap.Dropdown(dropdownToggleEl);
                });

                // 移动端菜单自动收起
                var navbarCollapse = document.getElementById("navbarNav");
                var navLinks = document.querySelectorAll(".navbar-nav .nav-link:not(.dropdown-toggle)");

                navLinks.forEach(function(link) {
                    link.addEventListener("click", function() {
                        if (window.innerWidth < 992) {
                            var bsCollapse = new bootstrap.Collapse(navbarCollapse, {
                                toggle: false
                            });
                            bsCollapse.hide();
                        }
                    });
                });
            }
        });
        </script>';
    }
}

// 如果直接访问此文件，显示调试信息
if (basename($_SERVER['PHP_SELF']) == 'navigation.php') {
    echo "<!DOCTYPE html><html><head><title>导航栏调试</title></head><body>";
    echo "<h2>导航栏调试信息</h2>";
    echo "<p>当前用户: " . htmlspecialchars($_SESSION['user_id'] ?? '未知') . "</p>";
    echo "<p>用户角色: " . implode(', ', $user_roles) . "</p>";
    echo "<p>数据库连接: " . ($db_connected ? '正常' : '失败') . "</p>";
    echo "<h3>导航栏预览:</h3>";

    // 添加Bootstrap CSS用于预览
    echo '<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">';
    echo '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">';

    // 渲染导航栏
    renderNavigationBar();

    // 添加Bootstrap JS
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>';
    echo "</body></html>";
    exit();
} else {
    // 被其他页面包含时，调用渲染函数
    renderNavigationBar();
}
?>